import { addResizeListener, removeResizeListener } from 'element-ui/src/utils/resize-event'

// 设置表格高度
const doResize = async (el, binding, vnode) => {
    // 获取表格Dom对象
    const { componentInstance: $table } = await vnode
    // 获取调用传递过来的数据
    const { value } = binding

    if (!$table.height) {
        throw new Error(`el-$table must set the height. Such as height='100px'`)
    }
    // 获取距底部距离（用于展示页码等信息）
    const bottomOffset = (value && value.bottomOffset) || 20

    if (!$table) return
    // 计算列表高度并设置
    const tableElement = document.querySelector('.el-table')
    const tableBorderHeight = tableElement.offsetHeight - tableElement.clientHeight // 表单上下border高度

    const wrapperElement = document.querySelector('.el-table__body-wrapper')
    const scrollbarHeight = wrapperElement.offsetHeight - wrapperElement.clientHeight // 横向滚动条高度

    const maxHeight = window.innerHeight - el.getBoundingClientRect().top - bottomOffset - tableBorderHeight
    const headerHeight = document.querySelector('.el-tableadaptive__header')?.offsetHeight ?? 0 // 表单head 实际高度
    const bodyHeight = document.querySelector('.el-table__body')?.offsetHeight ?? 0 // 表单body 实际高度

    const tableHeight = bodyHeight ? bodyHeight + headerHeight + scrollbarHeight + tableBorderHeight : 0
    const height = tableHeight && tableHeight < maxHeight ? tableHeight : maxHeight
    $table.layout.setHeight(height)

    $table.doLayout()
}

export default {
    // 初始化设置
    bind(el, binding, vnode) {
        // 设置resize监听方法
        el.resizeListener = async () => {
            await doResize(el, binding, vnode)
        }
        // 绑定监听方法到addResizeListener
        addResizeListener(window.document.body, el.resizeListener)
    },
    // 绑定默认高度
    async inserted(el, binding, vnode) {
        await doResize(el, binding, vnode)
    },
    async update(el, binding, vnode) {
        await doResize(el, binding, vnode)
    },
    // 销毁时设置
    unbind(el) {
        // 移除resize监听
        removeResizeListener(el, el.resizeListener)
    },
}
